import { lazy, useEffect, useState } from 'react';
import { buildRoutes, type RouteConfig } from './helper';
import { createBrowserRouter, RouterProvider } from 'react-router';
import asyncRoutesMap from './modules';
import { useAppStore } from '@/store/appStore';
import { AuthGuard } from './loader';
import { useMenuStore } from '@/store/menuStore';

const constRoutes: RouteConfig[] = [
  {
    path: '/login',
    element: lazy(() => import('@/views/login')),
  },
  {
    path: '/error/:name',
    element: lazy(() => import('@/components/Errors')),
  },
  {
    path: '*',
    loader: () => ({ name: 404 }),
    element: lazy(() => import('@/components/Errors')),
  },
];

export const AppRouter = () => {
  const dynamicRouter = useAppStore(state => state.dynamicRouter);
  const initMenus = useMenuStore(state => state.initMenus);
  const [routes, setRoutes] = useState<RouteConfig[]>([]);

  useEffect(() => {
    const loadRoutes = async () => {
      try {
        if (dynamicRouter) {
          // const apiRoutes = [];
          // const routeObjects = convertToRouteObjects(apiRoutes);
          setRoutes([]);
        } else {
          setRoutes(asyncRoutesMap);
        }
      } catch (err) {
        console.error('Failed to load routes:', err);
      }
    };

    loadRoutes();
  }, [dynamicRouter]);

  const allRoutes = buildRoutes([
    ...constRoutes,
    ...routes.map(route => ({ ...route, loader: AuthGuard })),
  ]);

  useEffect(() => {
    if (routes.length > 0) {
      initMenus(routes);
    }
  }, [routes, initMenus]);

  const router = createBrowserRouter(allRoutes);

  return <RouterProvider router={router} />;
};
